#include "QTimeWidget.h"
#include <QLayout>
#include <QPushButton>
#include "QTimeView.h"
#include "QTimeModel.h"
#include "QTimeDelegate.h"

QTimeWidget::QTimeWidget(int colCnt, QWidget *parent)
    : QWidget(parent)
{
    setAutoFillBackground(true);
    setBackgroundRole(QPalette::Window);

    _pModel = new QTimeModel(colCnt, this);
    _pView = new QTimeView(this);
    _pView->setObjectName(QLatin1String("qt_time_select_view"));
    _pView->setFrameStyle(QFrame::NoFrame);
    _pView->internalUpdate();
    _pView->setModel(_pModel);

    _pSelectionModel = _pView->selectionModel();
    _pDelegate = new QTimeDelegate(_pModel, this);
    _pView->setItemDelegate(_pDelegate);

    int value = _pModel->value();
    int row = -1, column = -1;
    _pModel->cellForValue(value, &row, &column);
    _pSelectionModel->clear();
    if (row != -1 && column != -1) {
        const auto& idx = _pModel->index(row, column);
        _pSelectionModel->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent);
    }
    
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setMargin(0);
    mainLayout->setSpacing(0);
    mainLayout->addWidget(_pView);

    connect(_pView, &QTimeView::valueChanged, this, &QTimeWidget::valueChanged);

    setFocusPolicy(Qt::StrongFocus);
    setFocusProxy(_pView);
    setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}

QTimeWidget::~QTimeWidget()
{}

void QTimeWidget::setMinValue(int value)
{
    if (_pModel)
        _pModel->setMinValue(value);
}

void QTimeWidget::setMaxValue(int value)
{
    if (_pModel)
        _pModel->setMaxValue(value);
}

void QTimeWidget::setCurrentValue(int value)
{
    _pModel->setValue(value);
    int row = -1, column = -1;
    _pModel->cellForValue(value, &row, &column);
    _pSelectionModel->clear();
    if (row != -1 && column != -1) {
        const auto& idx = _pModel->index(row, column);
        _pSelectionModel->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent);
    }
}

void QTimeWidget::setData(const QList<QString>& datas)
{
    if (_pModel)
        _pModel->setData(datas);
}

